package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import javax.jws.WebService;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebService(
        targetNamespace = "com.ruoyi.system.service", //wsdl命名空间
        name = "MesOps",                 //portType名称 客户端生成代码时 为接口名称
        serviceName = "IMesService",           //服务name名称
        portName = "mesServicePort",             //port名称
        endpointInterface = "com.ruoyi.system.service.IMesService")//指定发布webservcie的接口类，此类也需要接入@WebService注解
@Service
public class MesServiceImpl implements IMesService {

    private static final Logger log = LoggerFactory.getLogger(MesServiceImpl.class);

    @Value("${cloudpivot.message.template.workOrderMsg}")
    private String workOrderMsg;

    @Autowired
    private ITWorkOrderService tWorkOrderService;
    @Autowired
    private ITSrmWorkOrderService tSrmWorkOrderService;
    @Autowired
    private ITEquipmentMService itEquipmentMService;
    @Autowired
    private ITSamplingTaskService itSamplingTaskService;
    @Autowired
    private ITDingtalkMessageService itDingtalkMessageService;

    @Autowired
    private IDingTalkClientService dingTalkClientService;
    @Autowired
    private SimpMessagingTemplate messagingTemplate; // 通过messagingTemplate向浏览器发送消息

    @Autowired
    private ISysUserService userService;

    /**
     * 发送排产信息
     *
     * @param orderInfo
     */
    @Override
    public ResponseDto sendOrdeMessage(WorkOrderDTO orderInfo) {

        //Integer workline = Integer.parseInt(orderInfo.getMo_SortSeq());
        ResponseDto msgResponse = new ResponseDto();
        msgResponse.setId("0");
        msgResponse.setSuccess(0);
        /*检查参数*/
        if(orderInfo.getWorkStatus()== null){
            msgResponse.setMessage("发送失败，工单状态不能为空！");
            return msgResponse;
        }
        TWorkOrder tWorkOrder = new TWorkOrder();
        tWorkOrder.setMesNo(orderInfo.getWo_Code());
        tWorkOrder.setOrderNo(orderInfo.getMo_Code());
        tWorkOrder.setOperationNo(orderInfo.getOper_User());
        tWorkOrder.setOperationName(orderInfo.getOper_Name());
        tWorkOrder.setWorkStatus(orderInfo.getWorkStatus());
        tWorkOrder.setOrderLine(orderInfo.getMo_SortSeq());
        tWorkOrder.setGoodNo(orderInfo.getInv_Code());
        tWorkOrder.setGoodName(orderInfo.getInv_Name());
        tWorkOrder.setCategory(orderInfo.getInv_Std());
        tWorkOrder.setWorkLine(orderInfo.getOp_Seq());
        tWorkOrder.setWorkName(orderInfo.getOp_Name());
        tWorkOrder.setWorkNum(orderInfo.getWorkNum());
        tWorkOrder.setTeamLeader(orderInfo.getTeam_Leader());
        tWorkOrder.setTeamName(orderInfo.getTeam_Name());
        tWorkOrder.setTeamLeaderName(orderInfo.getTeamLeaderName());
        tWorkOrder.setCustomerProducts(orderInfo.getCustomerProducts());
        try {
            tWorkOrder.setCustomerDate(new SimpleDateFormat("yyyy-MM-dd").parse(orderInfo.getCustomerDate()));
        }catch (ParseException exception){
            log.error("日期转换CustomerDate出错",exception);
        }
        try {
            tWorkOrder.setStartTime_Schedule(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(orderInfo.getStartTime_Schedule()));
        }catch (ParseException exception){
            log.error("日期转换StartTime_Schedule出错:"+orderInfo.getStartTime_Schedule());
        }catch (NullPointerException exception){
            log.error(exception.getMessage(),orderInfo);
        }
        try {
            tWorkOrder.setEndTime_Schedule(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(orderInfo.getEndTime_Schedule()));
        }catch (ParseException exception){
            log.error("日期转换EndTime_Schedule出错:"+orderInfo.getEndTime_Schedule());
        }catch (NullPointerException exception){
            log.error(exception.getMessage(),orderInfo);
        }
        try {
            tWorkOrder.setStartTime_Actual(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(orderInfo.getStartTime_Actual()));
        }catch (ParseException exception){
            log.error("日期转换StartTime_Actual出错:"+orderInfo.getStartTime_Actual());
        }catch (NullPointerException exception){
            log.error(exception.getMessage(),orderInfo);
        }
        try {
            tWorkOrder.setEndTime_Actual(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(orderInfo.getEndTime_Actual()));
        }catch (ParseException exception){
            log.error("日期转换EndTime_Actual出错:"+orderInfo.getEndTime_Actual());
        }catch (NullPointerException exception){
            log.error(exception.getMessage(),orderInfo);
        }
        //新增工单
        TWorkOrder tWorkOrderDB = tWorkOrderService.selectTWorkOrderByMesNo(tWorkOrder.getMesNo());
        if(tWorkOrderDB == null){
            //新增记录
            tWorkOrder.setCreateTime(new Date());
            tWorkOrderService.insertTWorkOrder(tWorkOrder);
        }else {
            //如果工单状态已经存在相同的记录，不执行操作
            if(tWorkOrder.getWorkStatus() == tWorkOrderDB.getWorkStatus()){
                msgResponse.setSuccess(0);
                msgResponse.setMessage("发送失败，系统已经存在相同工单号和状态的记录！");
                return msgResponse;
            }
            //更新记录
            tWorkOrder.setId(tWorkOrderDB.getId());
            tWorkOrder.setUpdateTime(new Date());
            tWorkOrder.setCreateTime(new Date());
            tWorkOrderService.updateTWorkOrder(tWorkOrder);
        }
        //开工，报工，完工，3种状态才发消息
        if(     tWorkOrder.getWorkStatus().equals("5")
                || tWorkOrder.getWorkStatus().equals("6")
                || tWorkOrder.getWorkStatus().equals("7"))
        {
            //调用钉钉消息通知
            String dingTalkMessage = "";
            String markdownContent = "";
            DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            String workStatusName = getWorkStatusName(tWorkOrder.getWorkStatus());
            //推送websocket消息
            messagingTemplate.convertAndSend("/topic/publishNewOrder_WebSocket",tWorkOrder);

            /*String customerDate = "";
            try {
                customerDate = dateFormat.format(orderInfo.getCustomerDate());
            }catch (Exception exception){
                log.error("日期转换出错",exception);
            }*/
            markdownContent =
                    "### MES单据号："+tWorkOrder.getMesNo()+"  \n  " +
                            "### 生产订单号："+tWorkOrder.getOrderNo()+"  \n  " +
                            "### 订单行号："+tWorkOrder.getOrderLine()+"  \n  " +
                            "### 客户产品："+tWorkOrder.getCustomerProducts()+"  \n  " +
                            "### 件  号："+tWorkOrder.getCategory()+"  \n  " +
                            "### 存货名称："+tWorkOrder.getGoodName()+"  \n  " +
                            "### 客户交期："+orderInfo.getCustomerDate()+"  \n  " +
                            "### 工序行号："+ tWorkOrder.getWorkLine()+"  \n  " +
                            "### 工序名称："+tWorkOrder.getWorkName()+"  \n  " +
                            "### 工单状态："+workStatusName+"  \n  " +
                            "### 班组名称："+tWorkOrder.getTeamName()+"  \n  " +
                            "## 请关注以上信息，具体请到MES操作！";
            //"##### 发送时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").format(new java.sql.Timestamp(System.currentTimeMillis()));
            //增加钉钉消息记录
            TDingtalkMessage message = new TDingtalkMessage();
            message.copyWorkOrder(tWorkOrder);
            message.setStatus(0);//待通知
            message.setCreateTime(new Date());
            itDingtalkMessageService.insertTDingtalkMessage(message);
            String userDingTalkID = "";
            String leaderDingTalkID = "";
            /*try {
                //操作人员的ID
                userDingTalkID = userService.selectUserByLoginName(message.getOperationNo()).getDingtalkUserId();
            }catch (NullPointerException nullexception){
                log.error("获取操作人员ID失败",message);
                msgResponse.setMessage("发送失败，因为无法获取操作人员钉钉userid");
                return msgResponse;
            }*/
            try {
                //操作班长的ID
                leaderDingTalkID = userService.selectUserByLoginName(message.getTeamLeader()).getDingtalkUserId();
            }catch (NullPointerException nullexception){
                log.error("获取班长的ID失败",message);
                msgResponse.setMessage("发送失败，因为无法获取班长的钉钉userid");
                return msgResponse;
            }
            //找出下一个工序的班长
            try{
                //当前的工序行号
                Integer work_line_current_int = Integer.parseInt(tWorkOrder.getWorkLine());
                //下一个工序的行号
                String workline_next = String.format("%04d", work_line_current_int+10);
                log.info("下一道工序的workline是"+workline_next);
                //找到下个工序
                TWorkOrder workOrder_search = new TWorkOrder();
                workOrder_search.setOrderNo(tWorkOrder.getOrderNo());
                workOrder_search.setOrderLine(tWorkOrder.getOrderLine());
                workOrder_search.setWorkLine(workline_next);
                List<TWorkOrder> workorder_search_list = tWorkOrderService.selectTWorkOrderList(workOrder_search);
                if(!workorder_search_list.isEmpty()){
                    leaderDingTalkID += (","+userService.selectUserByLoginName(workorder_search_list.get(0).getTeamLeader()).getDingtalkUserId());
                }
                else
                {
                    log.info("找不到下一个环节的工单！");
                }
            }catch(Exception ex){

            }
            String result = dingTalkClientService.sendMarkDownMessageToDingTalk("176906604523922610,01275731194029253375,040050080320256880,080804392224126002,"+leaderDingTalkID,"工单提醒",markdownContent);

            //钉钉消息状态更新
            if(StringUtils.isNotBlank(result) && "ok".equals(result)){
                //更新通知状态为：已通知
                message.setStatus(1);//已通知
                itDingtalkMessageService.updateTDingtalkMessage(message);
            }
        }else {
            msgResponse.setMessage("消息已经被记录，但是不会发送，只有开工，报工，完工，3种状态才发消息！");
            msgResponse.setSuccess(1);
            return msgResponse;
        }
        msgResponse.setId(tWorkOrder.getOrderNo());
        msgResponse.setSuccess(1);
        msgResponse.setMessage("发送成功！");
        return  msgResponse;
    }
    /*发送报修工单接口*/
    @Override
    public ResponseDto sendEquipmentMDTOMessage(EquipmentMDTO equipmentMDTO) {
        ResponseDto msgResponse = new ResponseDto();
        msgResponse.setId("0");
        msgResponse.setSuccess(0);
        /*检查参数*/
        if(StringUtils.isBlank(equipmentMDTO.getMain_No())){
            msgResponse.setMessage("发送失败，维修单号不能为空！");
            return msgResponse;
        }
        TEquipmentM equipmentM = new TEquipmentM();
        equipmentM.setMainNo(equipmentMDTO.getMain_No());
        equipmentM.setEquipmentCode(equipmentMDTO.getEquipment_Code());
        equipmentM.setEquipmentName(equipmentMDTO.getEquipment_Name());
        equipmentM.setLocal(equipmentMDTO.getLocal());
        equipmentM.setRemark(equipmentMDTO.getRemark());
        equipmentM.setRepairman(equipmentMDTO.getRepairman());
        equipmentM.setStatus(equipmentMDTO.getStatus());
        equipmentM.setPhenomenon(equipmentMDTO.getPhenomenon());
        equipmentM.setTeamLeader(equipmentMDTO.getTeam_Leader());
        try {
            equipmentM.setUploadDate(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(equipmentMDTO.getUploadDate()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //校验维修单号是否存在
        TEquipmentM tmpEM = new TEquipmentM();
        tmpEM.setMainNo(equipmentMDTO.getMain_No());
        List<TEquipmentM>exsitEM = itEquipmentMService.selectTEquipmentMList(tmpEM);
        if(exsitEM != null && !exsitEM.isEmpty()){
            tmpEM = exsitEM.get(0);

            msgResponse.setSuccess(0);
            msgResponse.setMessage("发送失败，已经存在相同的维修单号记录！");
            return msgResponse;

            /*equipmentM.setId(tmpEM.getId());
            equipmentM.setCreateTime(tmpEM.getCreateTime());
            equipmentM.setUpdateTime(new Date());
            itEquipmentMService.updateTEquipmentM(equipmentM);*/
        }else {
            //新增设备报修
            equipmentM.setCreateTime(new Date());
            itEquipmentMService.insertTEquipmentM(equipmentM);
        }
        //调用钉钉消息通知
        String markdownContent = "";
        markdownContent =
                "### 维修单号："+equipmentM.getMainNo()+"  \n  " +
                        "### 设备编码："+equipmentM.getEquipmentCode()+"  \n  " +
                        "### 设备名称："+equipmentM.getEquipmentName()+"  \n  " +
                        "### 报修人："+equipmentM.getRepairman()+"  \n  " +
                        "### 报修位置："+equipmentM.getLocal()+"  \n  " +
                        "### 备注："+equipmentM.getRemark()+"  \n  " +
                        "## 请关注以上信息设备维修消息！";
        //发送钉钉消息给
        sendMessageByEMOrTask(msgResponse, markdownContent, "设备报修提醒", 491977378L);
        //发送钉钉消息给-班长
        //获取班长钉钉id
        SysUser teamLeaderUser = userService.selectUserByLoginName(equipmentM.getTeamLeader());
        if(teamLeaderUser != null){
            String userDingTalkID = teamLeaderUser.getDingtalkUserId();
            log.info("班长钉钉号:"+userDingTalkID);
            dingTalkClientService.sendMarkDownMessageToDingTalk(userDingTalkID, "设备报修提醒", markdownContent);
        }
        msgResponse.setId(equipmentM.getMainNo());
        return  msgResponse;
    }

    /*发送抽检任务提醒接口*/
    @Override
    public ResponseDto sendSpotCheckMessage(TSamplingTaskDTO tSamplingTaskDTO) {
        ResponseDto msgResponse = new ResponseDto();
        msgResponse.setId("0");
        msgResponse.setSuccess(0);
        /*检查参数*/
        if(StringUtils.isBlank(tSamplingTaskDTO.getMo_Code())){
            msgResponse.setMessage("发送失败，生产订单号不能为空！");
            return msgResponse;
        }
        TSamplingTask tSamplingTask = new TSamplingTask();
        tSamplingTask.setMoCode(tSamplingTaskDTO.getMo_Code());
        tSamplingTask.setMoSortseq(tSamplingTaskDTO.getMo_SortSeq());
        tSamplingTask.setInvStd(tSamplingTaskDTO.getInv_Std());
        tSamplingTask.setInvCode(tSamplingTaskDTO.getInv_Code());
        tSamplingTask.setInvName(tSamplingTaskDTO.getInv_Name());
        tSamplingTask.setCustomerproducts(tSamplingTaskDTO.getCustomerProducts());
        tSamplingTask.setOpName(tSamplingTaskDTO.getOp_Name());
        tSamplingTask.setOpSeq(tSamplingTaskDTO.getOp_Seq());
        tSamplingTask.setTeamName(tSamplingTaskDTO.getTeam_Name());
        tSamplingTask.setWorkStatus(tSamplingTaskDTO.getWorkStatus());
        tSamplingTask.setSamplingNo(tSamplingTaskDTO.getSampling_No());
        try {
            tSamplingTask.setCustomerDate(new SimpleDateFormat("yyyy-MM-dd").parse(tSamplingTaskDTO.getCustomerDate()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //校验维修单号是否存在
        TSamplingTask tmpEM = new TSamplingTask();
        tmpEM.setMoCode(tSamplingTaskDTO.getMo_Code());
        List<TSamplingTask>exsitEM = itSamplingTaskService.selectTSamplingTaskList(tmpEM);
        if(exsitEM != null && !exsitEM.isEmpty()){
            tmpEM = exsitEM.get(0);
            tSamplingTask.setId(tmpEM.getId());
            tSamplingTask.setCreateTime(tmpEM.getCreateTime());
            tSamplingTask.setUpdateTime(new Date());
            itSamplingTaskService.updateTSamplingTask(tSamplingTask);
        }else {
            //新增设备报修
            tSamplingTask.setCreateTime(new Date());
            itSamplingTaskService.insertTSamplingTask(tSamplingTask);
        }
        //调用钉钉消息通知
        String markdownContent = "";
        markdownContent =
                "### 生产订单号："+tSamplingTask.getMoCode()+"  \n  " +
                        "### 订单行号："+tSamplingTask.getMoSortseq()+"  \n  " +
                        "### 客户产品："+tSamplingTask.getCustomerproducts()+"  \n  " +
                        "### 件号："+tSamplingTask.getInvStd()+"  \n  " +
                        "### 客户交期："+tSamplingTask.getCustomerDate()+"  \n  " +
                        "### 工序行号："+tSamplingTask.getInvCode()+"  \n  " +
                        "### 工序名称："+tSamplingTask.getInvName()+"  \n  " +
                        "### 工单状态："+getWorkStatusName(tSamplingTask.getWorkStatus())+"  \n  " +
                        "### 班组名称："+tSamplingTask.getTeamName()+"  \n  " +
                        "### 抽检单号："+tSamplingTask.getSamplingNo()+"  \n  " +
                        "## 请关注以上抽检任务消息！";
        sendMessageByEMOrTask(msgResponse, markdownContent, "抽检任务提醒", 357496894L);
        msgResponse.setId(tSamplingTask.getId().toString());
        return  msgResponse;
    }
    @Override
    public ResponseDto sendSRMMessage(SRMWorkOrderDTO srmWorkOrderDTO) {

        ResponseDto msgResponse = new ResponseDto();
        msgResponse.setId("0");
        msgResponse.setSuccess(0);
        /*检查参数*/
        if(srmWorkOrderDTO.getStatus()== null){
            msgResponse.setMessage("发送失败，工单状态不能为空！");
            return msgResponse;
        }
        TSrmWorkOrder tWorkOrder = new TSrmWorkOrder();
        tWorkOrder.setSrmNo(srmWorkOrderDTO.getSRM_No());
        tWorkOrder.setMoCode(srmWorkOrderDTO.getMo_Code());
        tWorkOrder.setWorkStatus(srmWorkOrderDTO.getStatus());
        tWorkOrder.setMoSortSeq(srmWorkOrderDTO.getMo_SortSeq());
        tWorkOrder.setInvCode(srmWorkOrderDTO.getInv_Code());
        tWorkOrder.setInvName(srmWorkOrderDTO.getInv_Name());
        tWorkOrder.setInvStd(srmWorkOrderDTO.getInv_Std());
        tWorkOrder.setType(srmWorkOrderDTO.getType());
        tWorkOrder.setSupplier(srmWorkOrderDTO.getSupplier());
        //新增工单
        TSrmWorkOrder tWorkOrderDB = tSrmWorkOrderService.selectByWoCode(tWorkOrder.getSrmNo());
        if(tWorkOrderDB == null){
            //新增记录
            tWorkOrder.setCreateTime(new Date());
            tSrmWorkOrderService.insertTSrmWorkOrder(tWorkOrder);

            //调用钉钉消息通知
            String workStatusName = getWorkStatusName(tWorkOrder.getWorkStatus());
            String markdownContent =
                    "### MES单据号："+tWorkOrder.getSrmNo()+"  \n  " +
                            "### 生产订单号："+tWorkOrder.getMoCode()+"  \n  " +
                            "### 订单行号："+tWorkOrder.getMoSortSeq()+"  \n  " +
                            "### 件  号："+tWorkOrder.getInvStd()+"  \n  " +
                            "### 工单状态："+workStatusName+"  \n  " +
                            "### 检验类型："+tWorkOrder.getType()+"  \n  " +
                            "### 供应商："+tWorkOrder.getSupplier()+"  \n  " +
                            "## 请关注以上到货检验任务消息！";
            sendMessageByEMOrTask(msgResponse, markdownContent, "到货检验任务提醒", 357496894L);
            msgResponse.setId(tWorkOrder.getMoCode());
            msgResponse.setSuccess(1);
            msgResponse.setMessage("发送成功！");
        }else{
            msgResponse.setSuccess(0);
            msgResponse.setMessage("重复消息，不予发送！");
        }
        return  msgResponse;
    }

    /**
     * 设备报修和抽检任务消息通知
     * @param msgResponse
     * @param markdownContent
     * @param title
     */
    private void sendMessageByEMOrTask(ResponseDto msgResponse, String markdownContent, String title, long deptId){
        /*String userDingTalkID = "";
        //临时添加张经理为发送用户
        userDingTalkID = "080804392224126002,";
        //获取设备班下的所有人
        SysUser tmpUser = new SysUser();
        tmpUser.setDeptId(deptId);
        tmpUser.setStatus("0");
        List<SysUser> userList = userService.selectUserList(tmpUser);
        if(userList != null && !userList.isEmpty()){
            int i = userList.size();
            for(SysUser tmp : userList){
                i --;
                userDingTalkID += tmp.getDingtalkUserId();
                if(i > 0){
                    userDingTalkID += ",";
                }
            }
        }*/
        //发送给所有部门下的人
        String result = dingTalkClientService.sendMarkDownMessageToDingTalkbyDept(Long.toString(deptId),title,markdownContent);
        //临时发给张经理
        String result2 = dingTalkClientService.sendMarkDownMessageToDingTalk("080804392224126002", title, markdownContent);
        //钉钉消息状态更新
        if(StringUtils.isNotBlank(result) && "ok".equals(result)){
            //更新通知状态为：已通知
            msgResponse.setSuccess(1);
            msgResponse.setMessage("发送成功！");
        }else {
            msgResponse.setSuccess(0);
            String failInfo = result == null ? "" : "，失败原因：" + result;
            msgResponse.setMessage("发送失败" + failInfo);
        }
    }

    private String getWorkStatusName(String workStatus){
        String workStatusName = "未知";
        //0.未锁定1.已排程2.已锁定3.已派工4.已下达5.开工6.报工7.完工8.停工9.已暂停
        switch (workStatus){
            case "0":
                workStatusName="未锁定";
            case "1":
                workStatusName = "已排程";
                break;
            case "2":
                workStatusName = "已锁定";
                break;
            case "3":
                workStatusName = "已派工";
                break;
            case "4":
                workStatusName = "已下达";
                break;
            case "5":
                workStatusName = "开工";
                break;
            case "6":
                workStatusName = "报工";
                break;
            case "7":
                workStatusName = "完工";
                break;
            case "8":
                workStatusName = "停工";
                break;
            case "9":
                workStatusName = "已暂停";
                break;
            default:
                workStatusName="未知";
                break;
        }
        return workStatusName;
    }
}